# -*- coding: utf-8 -*-
import traceback
import sys
import os
import json

import util
from parse_coverage import read_coverage_report
from parse_unit_test import read_unit_test

# 考虑到不同项目可能会不同，统一定义在这，方便修改
# app模块的名称
app_name = "app"
# 覆盖率报告名称
report_xml_name = "reportRelease.xml"


# 获取Android工程目录
def get_project_path() -> str:
    path = os.path.abspath(__file__)
    while True:
        build_gradle = os.path.join(path, "build.gradle")
        build_gradle_kts = os.path.join(path, "build.gradle.kts")
        if util.exists(build_gradle) or util.exists(build_gradle_kts):
            return path
        else:
            # 逐级向上找目录
            dir_path = util.get_parent(path)
            if dir_path == "" or dir_path == path:
                # 已经到达根目录了
                return ""
            else:
                # 还有上级目录，继续while循环判断
                path = dir_path


def main():
    if len(sys.argv) < 2:
        print("please input a path to save data")
        return 1

    json_path = sys.argv[1]  # 单侧覆盖率结果存放文件，绝对路径

    # json_path = r"d:\workspace01\Android-APT\UnitTestCoverageDemo\unit_test_coverage\build\result.json"
    print(f"input path: {json_path}")

    # 执行gradlew，跑出单测覆盖率结果
    project_path = get_project_path()
    util.todir(project_path)
    util.execute(r".\gradlew clean")
    util.execute(r".\gradlew :app:koverXmlReportRelease")
    # util.execute(r".\gradlew :app:koverHtmlReportRelease")

    # 解析xml，获取单测覆盖率结果
    xml_path = os.path.join(
        project_path, app_name, "build", "reports", "kover", report_xml_name
    )
    if util.exists(xml_path):
        print(f"Xml report generated: {xml_path}")
        # 把xml中的覆盖率内容，解析成对应的json数据
        project_name = os.path.basename(project_path) # 获取项目名称
        json_data = read_coverage_report(xml_path, project_name)
        # 单元测试结果，解析成对应的json数据
        unit_test = read_unit_test(project_path)
        # 单元测试结果放在覆盖率报告里面
        json_data["tests"] = unit_test

        # 把json数据写入到外部指定的json文件中
        with open(json_path, "w") as json_file:
            json.dump(json_data, json_file)
    else:
        # 单元测试运行过程中出现了失败的情况：
        # print(f"Xml report not found: {xml_path}")
        raise RuntimeError(f"Xml report not found: {xml_path}")
        return 1

    print("----------------- android all missions complete -----------------")
    return 0


# main函数入口
if __name__ == "__main__":
    sys_ret = 0
    try:
        sys_ret = main()
    except Exception as e:
        print(e)
        traceback.print_exc()
        sys_ret = 1
    finally:
        sys.exit(sys_ret)
